package com.example.mapper;

import com.example.entity.Schedule;
import com.example.entity.Task;
import org.apache.ibatis.annotations.*;

import java.time.LocalDateTime;
import java.util.List;

@Mapper
public interface ScheduleMapper {


    List<Schedule> pageList(Integer page, Integer pageSize, String title, Integer id);

    @Select("select * from task where schedule_id=#{id}")
    List<Task> findTaskByScheduleId(Integer id);

    //计划展示
    @Select("select * from schedule where user_id=#{userId}")
    List<Schedule> selectByUserId(@Param("userId") Integer userId);

    //任务展示
    @Select("select * from task where schedule_id=#{scheduleId}")
    List<Task> selectByScheduleId(@Param("scheduleId") Integer scheduleId);

    @Insert("insert into schedule(user_id, title, progress, start_time) values " +
            "(#{userId},#{title},0,#{localDateTime})")
    void addSchedule(String title, Integer userId, LocalDateTime localDateTime);

    @Select("select id from schedule where user_id=#{userId} and title=#{title}")
    Integer findScheduleById(Integer userId, String title);

    @Select("select id from schedule where title=#{title} and user_id=#{userId}")
    Integer isExistSchedule(String title, Integer userId);

    @Delete("delete from schedule where user_id=#{id} and title=#{title}")
    void deleteSchedule(Integer id, String title);

    @Select("insert into task(schedule_id, description, resource_id, finished, title, image) " +
            "values (#{scheduleId},#{description},#{resourceId},0,#{title},#{image})")
    void addTasks(Task task);

    @Select("select COUNT(*) from schedule where user_id=#{id}")
    Integer getTotalSchedule(Integer id);

    @Select("select id from schedule where user_id=#{id}")
    List<Integer> getSchedule(Integer id);

    @Select("select COUNT(*) from task where schedule_id=#{scheduleId}")
    Integer getCountTask(Integer scheduleId);

    @Select("select COUNT(*) from task where schedule_id=#{scheduleId} and finished=1")
    Integer getNoFinishTask(Integer scheduleId);

    @Select("SELECT \n" +
            "    CASE \n" +
            "        WHEN COUNT(*) = 0 THEN '100%'\n" +
            "        ELSE SUM(progress) * 1.0 / COUNT(*) \n" +
            "    END AS average_progress\n" +
            "FROM \n" +
            "    schedule\n" +
            "WHERE \n" +
            "    progress <> 1 and user_id=#{id}")
    Float getTotalProgress(Integer id);

    @Update("update task set finished = 1 where resource_id=#{taskId};")
    void updateFinish(Integer taskId);

    @Select("select schedule_id from task where resource_id=#{taskId}")
    Integer getScheduleIdByTaskId(Integer taskId);

    @Select("SELECT SUM(CASE WHEN finished = 1 THEN 1 ELSE 0 END) * 1.0 / COUNT(*) AS finished_ratio\n" +
            "FROM task where schedule_id=#{id}")
    Float calculateProgress(Integer id);

    @Update("update schedule set progress = #{progress} where id=#{id};")
    void updateProgress(Float progress,Integer id);
}
